import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shortmovieapp/common.dart';
import 'package:shortmovieapp/data/localData.dart';
import 'package:shortmovieapp/data/requestData.dart';
import 'package:shortmovieapp/data/viewData.dart';
import 'package:shortmovieapp/http/request/appRequest.dart';
import 'package:shortmovieapp/myController/RequestServerController.dart';
import 'package:shortmovieapp/myController/appController.dart';
import 'package:shortmovieapp/myPages/shareView.dart';

class createMoviePage extends StatefulWidget {
  const createMoviePage({super.key});

  @override
  State<createMoviePage> createState() => _createMoviePageState();
}

class _createMoviePageState extends State<createMoviePage> {
  File? coverImg;
  Uint8List? coverImgBytes;
  String? title;
  String? movieType;
  String? desc;
  String? author;
  bool checkedBox = false;

  @override
  Widget build(BuildContext context) {
    double coverBtnSize = 80;

    return Scaffold(
        //backgroundColor: ,
        appBar: AppBar(
          titleTextStyle: const TextStyle(fontSize: 16),
          title: const Text("创建合集"),
          centerTitle: true,
          actions: [
            TextButton(
                onPressed: () => onClickMyMovieList(context),
                child: const Text("合集列表"))
          ],
        ),
        body: Container(
          padding: const EdgeInsets.fromLTRB(10, 20, 10, 0),
          child: Column(
            children: [
              Container(
                height: 30,
                alignment: Alignment.centerLeft,
                child: const Text("合集封面"),
              ),
              const SizedBox(height: 10),
              addCoverBtn(coverBtnSize, context),
              const SizedBox(height: 10),
              addTitleEditRow(),
              addUnderline(),
              const SizedBox(height: 10),
              addCategoryEditRow(context),
              const SizedBox(height: 20),
              Container(
                alignment: Alignment.centerLeft,
                child: const Text("合集简介"),
              ),
              const SizedBox(height: 10),
              addDescEdit(),
              const SizedBox(height: 10),
              addCheckBoxRow(),
              const SizedBox(height: 10),
              addSubmitBtn(context)
            ],
          ),
        ));
  }

  Container addSubmitBtn(BuildContext context) {
    return Container(
      width: 100,
      height: 50,
      decoration: BoxDecoration(
        //color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        //color: Colors.orange
      ),
      alignment: Alignment.center,
      child: ElevatedButton(
          style: const ButtonStyle(
              overlayColor: MaterialStatePropertyAll(Colors.transparent),
              backgroundColor: MaterialStatePropertyAll(Colors.deepOrange)),
          onPressed: () => onClickSubmit(context),
          child: const Text(
            "提交",
            style: TextStyle(color: Colors.white),
          )),
    );
  }

  Row addCheckBoxRow() {
    return Row(
      children: [
        Checkbox(
          value: checkedBox,
          onChanged: onCheckBox,
        ),
        const Text("已阅读《知识产权承诺书》")
      ],
    );
  }

  Container addDescEdit() {
    return Container(
      height: 100,
      color: Colors.black,
      child: MyInput(
        hint: "请输入合集简介（选填）",
        onValueChanged: onDescChanged,
      ),
    );
  }

  Container addCategoryEditRow(BuildContext context) {
    return Container(
        height: 30,
        child: Row(
          children: [
            Container(width: 60, child: const Text("合集分类")),
            Expanded(
                child: TextButton(
                    style: const ButtonStyle(
                        overlayColor:
                            MaterialStatePropertyAll(Colors.transparent)),
                    onPressed: () => onClickSelectType(context),
                    child: const Stack(
                      children: [
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "点击选择分类",
                            style: TextStyle(fontSize: 14, color: Colors.grey),
                          ),
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Icon(Icons.arrow_right),
                        )
                      ],
                    ))),
          ],
        ));
  }

  Padding addUnderline() {
    return const Padding(
        padding: EdgeInsets.only(left: 70),
        child: Divider(
          color: Colors.white30,
          height: 1,
          thickness: 0.5,
        ));
  }

  Container addTitleEditRow() {
    return Container(
        alignment: Alignment.centerLeft,
        height: 50,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(width: 60, child: const Text("合集标题")),
            MyInput(
              hint: "请输入标题",
              onValueChanged: onTitleChanged,
            ),
          ],
        ));
  }

  Container addCoverBtn(double coverBtnSize, BuildContext context) {
    return Container(
        height: coverBtnSize,
        alignment: Alignment.centerLeft,
        child: Stack(
          children: [
            Container(
              alignment: Alignment.center,
              color: Colors.white24,
              width: coverBtnSize,
              height: coverBtnSize,
              child: TextButton(
                  onPressed: () => onClickLoadCover(context),
                  style: const ButtonStyle(
                      overlayColor:
                          MaterialStatePropertyAll(Colors.transparent)),
                  child: Container(
                      height: 60,
                      child: const Column(children: [
                        Text("+",
                            style:
                                TextStyle(fontSize: 22, color: Colors.white)),
                        Text("添加封面",
                            style: TextStyle(fontSize: 12, color: Colors.white))
                      ]))),
            ),
            coverImg != null
                ? Image.memory(
                    coverImgBytes!,
                    width: coverBtnSize,
                    height: coverBtnSize,
                    fit: BoxFit.cover,
                  )
                : Container()
          ],
        ));
  }

  void onClickLoadCover(BuildContext context) async {
    Debug.log("on Click oadCover");
    final picker = ImagePicker();
    final pickedImage = await picker.pickImage(source: ImageSource.gallery);
    if (pickedImage != null) {
      var file = File(pickedImage.path);

      Uint8List bytes = await file.readAsBytes();
      //var str = utf8.decode(bytes);
      Future(() => {
            setState(() {
              this.coverImg = file;
              coverImgBytes = bytes;
            })
          });
    } else {
      Debug.log('No image selected.');
    }
  }
  // Future<void> _loadImage() async {
  //   final picker = ImagePicker();
  //   final pickedImage = await picker.pickImage(source: ImageSource.gallery);

  //   setState(() {
  //     if (pickedImage != null) {
  //       _image = File(pickedImage.path);
  //     } else {
  //       print('No image selected.');
  //     }
  //   });
  // }

  void onClickMyMovieList(BuildContext context)async {
    Debug.log("on Click my movie list");

    if(appController().recommendedPageData != null &&
    appController().recommendedPageData!.isNotEmpty)
    {        
      //TODO.
      var movie1 = appController().recommendedPageData?[0].itemDatas[0];
      if(movie1 != null)
      {
        var movieData = await RequestServerController().getShortMovieData(movie1.title);
        if(movieData != null)
        {
          Navigator.of(context).pushNamed(MyPageRoute.movieEdit,arguments: movieData);
        }
      }
    }
  }

  void onClickSelectType(BuildContext context) {
    Debug.log("on Click Select Categroy");
  }

  void onTitleChanged(value) {
    setState(() {
      title = value;
    });
    Debug.log("title value changed:$value");
  }

  void onDescChanged(value) {
    setState(() {
      desc = value;
    });
    Debug.log("desc value changed:$value");
  }

  void onCheckBox(bool? value) {
    Debug.log("checkbox:$value");
    setState(() {
      checkedBox = value ?? false;
    });
  }

  void onClickSubmit(BuildContext context) async {
    Debug.log("onClickSubmit");
    //TODO.remove
    movieType = MovieType.dushinaodong.stringValue;
    Debug.log("movieType:$movieType");

    if (isStringEmpty(title)) {
      showMyDialog(context, "消息", "标题不能为空", null);
      Debug.log("title is null");
      return;
    }
    if (isStringEmpty(movieType)) {
      showMyDialog(context, "消息", "请选择分类", null);
      Debug.log("movie type is null");
      return;
    }
    if (coverImg == null) {
      showMyDialog(context, "消息", "请选择封面", null);
      Debug.log("cover img is null");
      return;
    }
    if (!checkedBox) {
      showMyDialog(context, "消息", "请阅读《知识产权承诺书》并勾选", null);
      Debug.log("checkedBox false");
      return;
    }
    MovieProto movieProto = MovieProto(title!, 1, movieType!, desc ?? "-",
        author ?? "佚名", appController().user.name, getDateTime()
        // , coverImg!
        );

    //Debug.log("coverImg:${coverImg?.length}");
    var req = createMovieRequest(movieProto);
    var response = await req.sendFile(coverImg!.path);
    if (response.suc) {
      String responseData = response.data ?? "{}";
      MovieData movieData = MovieData.fromJsonString(responseData);

      Debug.log("创建合集成功:$movieData");
      Future(() {
        Navigator.of(context)
            .pushNamed(MyPageRoute.movieEdit, arguments: movieData);
      });
      // var coverReq = upploadMovieCover(movieItemData.movieId,movieItemData.title);
      // var result = await coverReq.sendFile(coverImg!.path);
      // if(result.suc){
      //   Debug.log("上传封面成功:$movieItemData");
      //   responseData = result.data??"{}";
      //   var movieData = MovieItemData.fromJsonString(responseData);
      //   Future(() {
      //     Navigator.of(context).pushNamed(MyPageRoute.movieEdit,arguments: movieItemData);
      //   });
      //  }
    } else {
      Debug.log("创建合集失败:${response.message}");
    }
  }
}
